﻿using System;
using System.IO;
using Wise.TimeWarrior.DTO;
using Wise.TimeWarrior.Interfaces;
using Wise.TimeWarrior.Helpers;
namespace Wise.TimeWarrior.Impl
{
    /// <summary>
    /// <see cref="IConfiguration"/>
    /// </summary>
    public class ConfigurationService : IConfiguration
    {
        private static string APPLICATION_FOLDER_NAME = @"TimeWarrior";
        private static string APPLICATION_CONFIGURATION_FILE_NAME = @"config.ser";

        /// <summary>
        /// conains application configuration folder path
        /// </summary>
        public string ApplicationConfigurationFolderPath
        {
            get
            {
                return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), APPLICATION_FOLDER_NAME);
            }
        }

        /// <summary>
        /// conains application configuration file path
        /// </summary>
        public string ApplicationConfigurationFilePath
        {
            get
            {
                return Path.Combine(ApplicationConfigurationFolderPath, APPLICATION_CONFIGURATION_FILE_NAME);
            }
        }

        /// <see cref="IConfiguration.SaveConfiguration(ConfigurationDto)"/>
        public void SaveConfiguration(ConfigurationDto config)
        {
            bool configPreparationStatus = PrepareAndCheckDirectories();

            SerializationHelper.Serialize<ConfigurationDto>(ApplicationConfigurationFilePath, config);
        }

        /// <see cref="IConfiguration.ReadConfiguration()"/>
        public ConfigurationDto ReadConfiguration()
        {
            bool configPreparationStatus = PrepareAndCheckDirectories();
            if (configPreparationStatus)
            {

                return SerializationHelper.Deserialize<ConfigurationDto>(ApplicationConfigurationFilePath);


            }
            else
            {
                ConfigurationDto cfg = new ConfigurationDto();
                cfg.MinutesOfWorkingHouersPerDay = 8 * 60;
                cfg.MinutesOfFreeTimePerDay = 15;
                cfg.WorkingHoursStartWatchTime = "8:00";
                cfg.WorkingHoursEndWatchTime = "16:00";
                cfg.PathToDataStore = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), APPLICATION_FOLDER_NAME);
                SaveConfiguration(cfg);
                return cfg;
            }
        }

        private bool PrepareAndCheckDirectories()
        {
            if (!Directory.Exists(ApplicationConfigurationFolderPath))
            {
                Directory.CreateDirectory(ApplicationConfigurationFolderPath);
            }
            return File.Exists(ApplicationConfigurationFilePath);
        }
    }
}
